/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.application;

import com.jb.web.bean.FloatPanel;
import com.jb.web.bean.HtmlItem;
import com.jb.web.bean.Page;
import com.jb.web.bean.TabbedPanel;
import com.jb.web.context.WebContext;
import com.jb.web.model.Securable;
import com.jb.web.session.Session;


/**
 * JB utitilies methods used for various occasions.
 *
 * @author anpwang
 * @version 1.0
 */
public class SystemUtil {
    public static int authorize(WebContext pCtx) {
        return pCtx.getSession().getSecurityManager().authorize(pCtx, pCtx.getSession().getContentOwner(),
            pCtx.getSession().getUser());
    }

    /**
     * Determines whether a session user has access to a resource. It is the
     * responsbility of item to determine the access logic.
     * This method can be accessed from el via jb:authorized
     * @param session
     * @param item
     * @return
     */
    public static boolean isAuthorized(Session session, Object item) {
        boolean authorized = session.isAuthenticated();

        if (!authorized) {
            return false;
        }

        if (item instanceof Securable) {
            authorized = authorized &&
                ((Securable) item).isAuthorized(session.getContext(), session.getUser(), session.getContentOwner());
        }
        return authorized;
    }

    //enable to add scope values from el.
    //jb:scopeAttr(context, 'test', 'value')
    public static boolean setScopeAttr(Object scope, Object key, Object value) {
        if (scope instanceof Session) {
            ((Session) scope).addAttribute("" + key, value);

            return true;
        }

        if (scope instanceof WebContext) {
            ((WebContext) scope).addParameter(key, value);

            return true;
        }

        return false;
    }

    /**
     * Show a dialog box on current page. This is a runtime function. When in design time,
     * calling this function yield no effect at all.
     *
     * It searches for the panel name from current respond tree, if found, the panel will be used.
     * if not found, the page name is used to locate the panel. It is important to
     * make sure the client id is unique for the panel to be displayed.
     *
     * If there is a clash in client id, the result to this call is unknown.
     *
     *
     * @param pCtx context container
     * @param dailogPageName page name, such as editMessage.xsp
     * @param panelName client id of a FloatPanel defined in the page.
     * This is the panel gets displayed.
     */
    public static HtmlItem showDialogBox(WebContext pCtx, String dailogPageName, String panelName) {
        //if it is design 
        if (!pCtx.isRunTime()) {
            return null;
        }

        //locate the panel in current respond tree
        HtmlItem item = (HtmlItem) pCtx.getRespondTree();
        HtmlItem styleEditorPanel = null;

        //if(dailogPageName.equals(item.getId()))
        styleEditorPanel = (HtmlItem) item.getDescendantByClientId(panelName);

        //if not found in the respondTree, then page name is used
        if (styleEditorPanel == null) {
            try {
                styleEditorPanel = (HtmlItem) pCtx.getSession().getPage(pCtx, dailogPageName, false)
                                                  .getDescendantByClientId(panelName);
            } catch (PageSecurityException e) {
                styleEditorPanel = new TabbedPanel();
                styleEditorPanel.setValue(e.getMessage());
                styleEditorPanel.setId("dummy");

                return styleEditorPanel;
            }

            //if styleEditorPanel found, a clone of it is added to current respond tree
            //and it is a float panel
            if (styleEditorPanel instanceof FloatPanel) {
                styleEditorPanel = (HtmlItem) styleEditorPanel.clone(pCtx, false, false);

                //styleEditorPanel.setDisplayStyle("none");
                item.addChild(styleEditorPanel);
            }
        }

        //make it visible. How this panel is rendered is defined by the panel itself
        //for example, one can set onLoad of the panel to be
        
        //
        if (styleEditorPanel instanceof FloatPanel) {
            //
            //disable the page reopended back for allowing popup windows.
            //the renderer will not render the event handler back hence disabled
            //
            pCtx.getSession().setCustomizable(false);
            pCtx.getSession().setPageInDesign((Page) item);
            styleEditorPanel.setVisible("true");

            //styleEditorPanel.setDisplayStyle("none");
        }

        return styleEditorPanel;
    }
}
